package com.addressbook.fw;

import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

public class GroupHelper extends HelperWithWebDriverBase {

	private Groups groupModel;
	private int lastGroupId;
	
	public GroupHelper(ApplicationManager manager) {
		super(manager);
		this.getGroups();
//		try {
//			lastGroupId = Integer.parseInt(manager.getHibernateHelper().getLastGroupId());
//		} catch (NumberFormatException e) {
//			e.printStackTrace();
//		} finally {
//			lastGroupId = 1;
//		}
		
	}

	public void createGroup(GroupObject group) {
		manager.getNavigationHelper().openGroupPage();
		initGroupCreation();
		fillGroupForm(group);
		submitGroupCreation();
		manager.getNavigationHelper().openGroupPage();
//		System.out.println(groupModel);
//		lastGroupId = lastGroupId + 1;
//		group.setId("" + lastGroupId);
		groupModel = groupModel.withAdded(group);
	}

	private void submitGroupCreation() {
		click(By.name("submit"));
	}

	private void fillGroupForm(GroupObject groupObject) {
		fillField("group_name", groupObject.name);
		fillField("group_header", groupObject.header);
		fillField("group_footer", groupObject.footer);
	}

	private void initGroupCreation() {
		click(By.name("new"));
	}

	public void deleteGroup(GroupObject group) {
		manager.getNavigationHelper().openGroupPage();
		checkGroup(group);
		click(By.name("delete"));
		manager.getNavigationHelper().openGroupPage();
		groupModel = groupModel.without(group);
	}

	public void modifyGroup(GroupObject oldGroup, GroupObject newGroup) {
		manager.getNavigationHelper().openGroupPage();
		initGroupModification(oldGroup);
		fillGroupForm(newGroup);
		submitGroupModification();
		manager.getNavigationHelper().openGroupPage();
		groupModel = groupModel.without(oldGroup).withAdded(newGroup);
	}

	private void submitGroupModification() {
		click(By.name("update"));
	}

	private void initGroupModification(GroupObject group) {
		checkGroup(group);
		click(By.name("edit"));
	}

	private void checkGroup(GroupObject group) {
		click(By.xpath("//input[@type='checkbox' and @name='selected[]' and @value='" + group.getId() + "']"));
	}

	public Groups getGroups() {
		if (groupModel == null) {
			groupModel = manager.getHibernateHelper().getGroups();
		}
		return groupModel;		
	}
	
	public Groups getUIGroups() {
		HashSet<GroupObject> set = new HashSet<GroupObject>();
		manager.getNavigationHelper().openGroupPage();
		List<WebElement> checkboxes = findElements(By.name("selected[]"));
		for (WebElement checkbox : checkboxes) {
			String title = checkbox.getAttribute("title");
			Pattern p = Pattern.compile(".*\\((.*)\\)");
			Matcher m = p.matcher(title);
			if (m.matches()) {
				title = m.group(1);
			}
			GroupObject group = new GroupObject().setName(title).setId(checkbox.getAttribute("value"));
			set.add(group);
		}
		return new Groups(set);
	}

}
